package com.kun.utils;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.OutputStream;
import java.util.Date;

@Component
public class CaptchaUtils  {

    private String code;

    @Value("${file.captcha.captchaPicturePath}")
    private String captchaPicturePath;

    @Value("${file.captcha.captchaFilePrefix}")
    private String captchaFilePrefix;


    //返回访问路径
    public String createCode() {
        //1. 定义图形验证码的长和宽
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 4, 4);
        //2. 自定义验证码内容为四则运算方式
        captcha.setGenerator(new MathGenerator(1));
//        String projectPath = System.getProperty("user.dir");
        String simpleUUID = IdUtil.simpleUUID();
        String path=captchaPicturePath+"captcha_"+simpleUUID+".png";
        //3. 图形验证码写出，可以写出到文件，也可以写出到流
        captcha.write(path);
        code=captcha.getCode();
        return captchaFilePrefix+"captcha_"+simpleUUID+".png";
    }

    public String getCode() {
        return code;
    }

    public boolean verify(String userInputCode) {
        try {
            int userCode = Integer.parseInt(userInputCode);
            String code_final=code.substring(0,code.length()-1);
            int a = Integer.parseInt(code_final.substring(0, 1));
            String b = code_final.substring(1, 2);
            int c = Integer.parseInt(code_final.substring(2, 3));
            int result=0;
            switch (b){
                case "+":result=a+c;break;
                case "-":result=a-c;break;
                case "*":result=a*c;break;
            }
            if (result==userCode){
                return true;
            }else {
                return false;
            }

        }catch (Exception e){
            return false;
        }
    }

    public void write(OutputStream out) {

    }
}
